package com.starlink.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.starlink.context.SessionContext;
import com.starlink.utils.DateUtils;
import com.starlink.utils.IDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * @author macbook
 */
@Slf4j
@Component
public class AutoFillMetaObjectHandler implements MetaObjectHandler {

    private static final String ID = "id";
    private static final String CREATE_USER = "createUser";
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_USER = "updateUser";
    private static final String UPDATE_TIME = "updateTime";
    private static final String DELETED = "deleted";

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = SessionContext.getLoginAccountId();
        if (metaObject.getValue(ID) == null) {
            this.setFieldValByName(ID, IDUtils.getId(), metaObject);
        }
        if (metaObject.getValue(CREATE_USER) == null) {
            this.setFieldValByName(CREATE_USER, userId, metaObject);
        }
        if (metaObject.getValue(UPDATE_USER) == null) {
            this.setFieldValByName(UPDATE_USER, userId, metaObject);
        }
        if (metaObject.getValue(CREATE_TIME) == null) {
            this.setFieldValByName(CREATE_TIME, DateUtils.getNowDate(), metaObject);
        }
        if (metaObject.getValue(UPDATE_TIME) == null) {
            this.setFieldValByName(UPDATE_TIME, DateUtils.getNowDate(), metaObject);
        }
        this.setFieldValByName(DELETED, 0, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.getValue(UPDATE_USER) == null) {
            this.setFieldValByName(UPDATE_USER, SessionContext.getLoginAccountId(), metaObject);
        }
        if (metaObject.getValue(UPDATE_TIME) == null) {
            this.setFieldValByName(UPDATE_TIME, DateUtils.getNowDate(), metaObject);
        }

    }
}
